package com.nativetalk.service.three.member.register;

import com.nativetalk.base.RetInfo;
import com.nativetalk.bean.member.TdNtMember;
import com.nativetalk.bean.member.TdNtMemberRegister;
import com.nativetalk.bean.member.TdNtMemberThirdRegister;
import com.nativetalk.bean.member.TdNtMemberToken;
import com.nativetalk.bean.user.TdNtUserLoginLog;
import com.nativetalk.common.Constants;
import com.nativetalk.common.ValidationMessages;
import com.nativetalk.common.util.CommonUtil;
import com.nativetalk.common.util.MemcachedUtils;
import com.nativetalk.dao.TdNtMemberDao;
import com.nativetalk.dao.TdNtUserLoginLogDao;
import com.nativetalk.service.member.register.MemberRegisterService;
import com.nativetalk.service.member.register.MemberRegisterServiceImpl;
import com.tls.tls_sigature.tls_sigature;
import org.apache.commons.collections.map.HashedMap;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * Created by lizhun on 16/6/23.
 */
@Service
public class ThreeMemberRegisterServiceImpl implements ThreeMemberRegisterService {
    @Resource
    private TdNtMemberDao tdNtMemberDao;
    @Resource
    private TdNtUserLoginLogDao tdNtUserLoginLogDao;

    private static Logger logger = Logger.getLogger(MemberRegisterServiceImpl.class);
    @Override
    public RetInfo thirdregister(TdNtMemberThirdRegister tdNtMemberThirdRegister, String ip) {
        String logInfo = this.getClass().getName() + ":thirdregister:";
        logger.info("======" + logInfo + "begin======");
        RetInfo retInfo = new RetInfo();
        try {
            //查询用第三方登录的老账户
            TdNtMember oldMemberRegister = tdNtMemberDao.findTdNtMemberByThirdToken(tdNtMemberThirdRegister.getThird_token());
            //查询用第三方登录的新账户
            TdNtMember memberRegister;
            Integer now_login_type = tdNtMemberThirdRegister.getNowLoginType();
            if(null != now_login_type){
                memberRegister = tdNtMemberDao.findTdNtMemberByLoginTypeAndThirdToken(tdNtMemberThirdRegister.getThird_token(),
                    now_login_type);
            }
            else {
                memberRegister = null;
            }

            /**
             * 判断用户是否已存在
             */
            //用户已存在
            if (null != memberRegister || null != oldMemberRegister) {
                TdNtMember tdNtMember;
                if(null != memberRegister){
                    tdNtMember = memberRegister;
                }
                else{
                    tdNtMember = oldMemberRegister;
                    if(null != now_login_type){
                        /**
                         * 更新用户第三方登录后的账号绑定信息
                         */
                        Map<String,Object> mapParams = new HashedMap();
                        mapParams.put("memb_id",tdNtMember.getMemb_id());
                        mapParams.put("thirdParty_type",now_login_type);
                        mapParams.put("third_token",tdNtMemberThirdRegister.getThird_token());
                        tdNtMemberDao.updateMemberThirdPartyBindStatus(mapParams);
                    }
                }

                TdNtUserLoginLog tdNtUserLoginLog = new TdNtUserLoginLog();
                tdNtUserLoginLog.setUser_id(tdNtMember.getMemb_id());
                tdNtUserLoginLog.setUser_type(1);
                tdNtUserLoginLog.setYyyymm(CommonUtil.getMonth(new Date()));
                tdNtUserLoginLog.setLogin_ip(ip);
                tdNtUserLoginLog.setUid(tdNtMember.getUid());
                if (tdNtMember.getMemb_islock().equals(Constants.MemberLockStatus.unlocked)) {
                    /**
                     * 更新用户token,当前登录的第三方token,当前登录方式
                     */
                    TdNtMemberToken tdNtMemberToken = new TdNtMemberToken();
                    tdNtMemberToken.setMemb_id(tdNtMember.getMemb_id());
                    tdNtMemberToken.setToken(CommonUtil.getToken());
                    tdNtMemberToken.setEqu_client_id(tdNtMemberThirdRegister.getEqu_client_id());
                    tdNtMemberToken.setEqu_type(tdNtMemberThirdRegister.getEqu_type());
                    tdNtMemberToken.setThird_token(tdNtMemberThirdRegister.getThird_token());
                    tdNtMemberToken.setNowLoginType(now_login_type);

                    /**
                     * 删除把用户对象放入memcached原有用户对象
                     * 注意：一定要先删除缓存，然后再更新数据库中的token（因为删除缓存有可能失败，这时就不能更新数据库中的token）
                     */
                    if(null != tdNtMember.getToken()) {
                        MemcachedUtils.delete(tdNtMember.getToken());
                    }

                    tdNtMemberDao.updateTdNtMemberInfo(tdNtMemberToken);
                    // 新注册用户有手机号的才分配客服，通过第三方注册的新用户没有手机号，因此这里不分配助教

                    /**
                     * 把用户对象放入memcached
                     */
                    tdNtMember.setToken(tdNtMemberToken.getToken());
                    tdNtMember.setEqu_client_id(tdNtMemberToken.getEqu_client_id());
                    tdNtMember.setEqu_type(tdNtMemberToken.getEqu_type());
                    MemcachedUtils.add(tdNtMember.getToken(), tdNtMember, 20 * 24 * 60 * 60);


                    Map<String,Object> map = new HashMap<>();
                    map.put("token",tdNtMemberToken.getToken());
                    map.put("sig", tls_sigature.getUsersig(Constants.member + tdNtMember.getMemb_id()));
                    if (tdNtMember.getMemb_phone() != null) {
                        map.put("phone",tdNtMember.getMemb_phone());
                    } else {
                        map.put("phone", "");
                    }

                    map.put("Identifier", Constants.member + tdNtMember.getMemb_id());
                    map.put("uid", tdNtMember.getUid());
                    retInfo.setMark(ValidationMessages.getValue("MARKYES"));
                    retInfo.setTip(ValidationMessages.getValue("LOGIN.SUCCESS"));
                    retInfo.setObj(map);

                    tdNtUserLoginLog.setIs_success("0");
                    tdNtUserLoginLog.setLogin_failer_desc("登录成功");

                } else {
                    retInfo.setMark(ValidationMessages.getValue("MARKNO"));
                    retInfo.setTip(ValidationMessages.getValue("LOGIN.ERROR"));
                    tdNtUserLoginLog.setIs_success("1");
                    tdNtUserLoginLog.setLogin_failer_desc("账号被锁定");
                }
                tdNtUserLoginLogDao.insertTdNtUserLoginLog(tdNtUserLoginLog);
            }
            //用户不存在
            else {

                TdNtMemberRegister tdNtMemberRegister = new TdNtMemberRegister();
                tdNtMemberRegister.setEqu_client_id(tdNtMemberThirdRegister.getEqu_client_id());
                tdNtMemberRegister.setEqu_type(tdNtMemberThirdRegister.getEqu_type());
                tdNtMemberRegister.setMemb_balance(new BigDecimal("0"));
                /**
                 * 用户注册
                 */
                tdNtMemberRegister.setMemb_islock(Constants.MemberLockStatus.unlocked);
                tdNtMemberRegister.setMemb_invite_code(CommonUtil.getInviteCode());
                tdNtMemberRegister.setMemb_register_month(CommonUtil.getMonth(new Date()));
                tdNtMemberRegister.setToken(CommonUtil.getToken());
                if (tdNtMemberThirdRegister.getMemb_head_portrait()!=null) {
                    tdNtMemberRegister.setMemb_head_portrait(tdNtMemberThirdRegister.getMemb_head_portrait());
                } else {
                    tdNtMemberRegister.setMemb_head_portrait("/nativetalk/head/head.png");
                }
                if (tdNtMemberThirdRegister.getMemb_name()!=null) {
                    tdNtMemberRegister.setMemb_name(tdNtMemberThirdRegister.getMemb_name());
                } else {
                    tdNtMemberRegister.setMemb_name("nativetalk");
                }
                if (tdNtMemberThirdRegister.getMemb_sex()!=null) {
                    tdNtMemberRegister.setMemb_sex(tdNtMemberThirdRegister.getMemb_sex());
                } else {
                    tdNtMemberRegister.setMemb_sex(Constants.MemberGender.male);
                }
                tdNtMemberRegister.setThird_token(tdNtMemberThirdRegister.getThird_token());
                tdNtMemberRegister.setNowLoginType(now_login_type);
                tdNtMemberRegister.setMemb_birthday(new Timestamp(new Date().getTime()));
                tdNtMemberRegister.setUid(UUID.randomUUID().toString());
                tdNtMemberDao.insertTdNtMember(tdNtMemberRegister);

                TdNtMember tdNtMember;
                if(null != now_login_type){
                    /**
                     * 更新用户第三方登录后的账号绑定信息
                     */
                    Map<String,Object> mapParams = new HashedMap();
                    mapParams.put("memb_id",tdNtMemberRegister.getMemb_id());
                    mapParams.put("thirdParty_type",now_login_type);
                    mapParams.put("third_token",tdNtMemberThirdRegister.getThird_token());
                    tdNtMemberDao.updateMemberThirdPartyBindStatus(mapParams);

                    tdNtMember = tdNtMemberDao.findTdNtMemberByLoginTypeAndThirdToken(tdNtMemberThirdRegister.getThird_token(), now_login_type);
                }
                else {
                    tdNtMember = tdNtMemberDao.findTdNtMemberByThirdToken(tdNtMemberThirdRegister.getThird_token());
                }

                Map<String,Object> map = new HashMap<>();
                map.put("token",tdNtMemberRegister.getToken());
                map.put("sig", tls_sigature.getUsersig(Constants.member + tdNtMemberRegister.getMemb_id()));
                map.put("Identifier", Constants.member + tdNtMemberRegister.getMemb_id());
                map.put("phone", "");
                map.put("uid", tdNtMemberRegister.getUid());
                retInfo.setMark(ValidationMessages.getValue("MARKYES"));
                retInfo.setTip(ValidationMessages.getValue("REGISTER.SUCCESS"));
                retInfo.setObj(map);

                MemcachedUtils.add(tdNtMember.getToken(),tdNtMember,20*24*60*60);

                //记录登录日志
                TdNtUserLoginLog tdNtUserLoginLog = new TdNtUserLoginLog();
                tdNtUserLoginLog.setUser_id(tdNtMember.getMemb_id());
                tdNtUserLoginLog.setUser_type(1);//1学生，2老师
                tdNtUserLoginLog.setYyyymm(CommonUtil.getMonth(new Date()));
                tdNtUserLoginLog.setLogin_ip(ip);
                tdNtUserLoginLog.setIs_success("0");
                tdNtUserLoginLog.setLogin_failer_desc("登录成功");
                tdNtUserLoginLog.setAccount(tdNtMemberThirdRegister.getThird_token());
                tdNtUserLoginLog.setUid(tdNtMember.getUid());
                tdNtUserLoginLogDao.insertTdNtUserLoginLog(tdNtUserLoginLog);
            }
        }  catch (Exception e) {
            retInfo.setMark(ValidationMessages.getValue("MARKERROR"));
            retInfo.setTip(ValidationMessages.getValue("TIPERROR"));
            logger.error(e.getMessage(),e);
        }
        logger.info("======" + logInfo + "end======");
        return retInfo;
    }
}
